package com.bookseek.xreader.fucker;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.bookseek.xreader.consts.XreaderConts;
import com.bookseek.xreader.params.ExtraParams;
import com.bookseek.xreader.po.TMetaPo;
import com.bookseek.xreader.service.dk.BdocService;
import com.bookseek.xreader.service.dk.TMetaService;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.JkhlUtils;
import com.bookseek.xreader.utils.OkHttpUtils;
import com.bookseek.xreader.vo.HttpRetVo;
import com.bookseek.xreader.vo.MetaTaskVo;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import okhttp3.internal.concurrent.Task;

public class MetaWorker extends Worker {


    public ConcurrentHashMap<Integer,Boolean> DDOC_TASKS = new ConcurrentHashMap<>();
    public MetaWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }


    public MetaTaskVo dealTMetaTaskBDoc(TMetaPo po){
        MetaTaskVo taskVo = new MetaTaskVo();
        taskVo.metaPo = po;
        String platName = po.plat != null && po.plat.equals(1) ? "YNOTE" : po.plat+"";
        //判断是否已经下载完毕
        if(po.dflag != null && po.dflag.equals(XreaderConts.TMETA_DLAG_OK)){
            DLog.info("id=",po.id,"bcount=",po.bcount,"plat=",po.plat,"已处理OK",po.bkey);
            taskVo.success = true;
            return taskVo;
        }
        if(JkhlUtils.isBlank(po.resource)){
            DLog.error("id=",po.id,"resource 为空，不执行数据处理");
            taskVo.success = true;
            return taskVo;
        }
        if(po.bmax != null && po.bmin != null && po.bcount != null && JkhlUtils.notBlank(po.bids)){
            try{
                Integer countCidNum = BdocService.getInstance().countRowidStr(po.bids);
                if(countCidNum != null && countCidNum >= po.bcount){
                    DLog.info("数据库已经存在 id=",po.id,"bcount=",po.bcount,"plat=",po.plat,"已处理OK");
                    po.dflag = XreaderConts.TMETA_DLAG_OK;
                    taskVo.success = true;
                    return taskVo;
                }
            }catch (Exception e){
                DLog.error("dealTMetaTaskBDoc countCidNum e=",e.getMessage());
                e.printStackTrace();
            }
        }

        HttpRetVo retVo = OkHttpUtils.getInstance().downGetExecute(po.resource);
        int dataLen = retVo.datas != null  ? retVo.datas.length : 0;
        if(retVo.success && retVo.datas != null && retVo.datas.length > 0){
            BdocService.getInstance().parseDownDataBdoc(po,retVo.datas);
        }
        taskVo.msg = retVo.msg;
        taskVo.statusCode = retVo.statusCode;;
        taskVo.success = retVo.success;
        taskVo.downDataLen = dataLen;
        DLog.info("id=",po.id,"bcount=",po.bcount,"plat=",platName,"处理结果",po.bkey,"retVo.success=",retVo.success,"dataLen=",dataLen);
        return taskVo;
    }
    @NonNull
    @Override
    public Result doWork() {
        // 从输入数据中获取参数
        Data inputData = getInputData();
        Integer btype = inputData.getInt("btype",-1);
        if(DDOC_TASKS.contains(btype)){
            DLog.info("DDOC_TASKS 任务 btype=",btype," 已经在运行,返回 Result.failure()");
            //return Result.retry();
            return Result.failure();
        }
        if(!DDOC_TASKS.contains(btype)){
            DDOC_TASKS.put(btype,true);
        }
        Long startTm = System.currentTimeMillis();
        DLog.info("Start Run doWork btype=",btype);
        boolean isOk = false;
        boolean networkErr = false;

        try{
            //Map<String, List<TMetaPo>> shiciMetaMap = TMetaService.getInstance().getShiciDownMetaMap();
            Map<String, List<TMetaPo>> shiciMetaMap = TMetaService.getInstance().getDownMetaMapByBtype(btype);
            List<String> bkeys = shiciMetaMap.keySet().stream().sorted().collect(Collectors.toList());
            //已经下载过的任务bkey
            Set<String> downOkBkeys = new HashSet<>();
            for(String bkey : bkeys){
                if(networkErr){
                    break;
                }
                DLog.info("Start Deal bkey=",bkey);
                List<TMetaPo> todoPos = shiciMetaMap.get(bkey);
                boolean downOk = todoPos.stream().anyMatch(d-> Objects.equals(d.dflag,XreaderConts.TMETA_DLAG_OK));
                if(downOk){
                    DLog.info("bkey===> haveDown ok",bkey);
                    downOkBkeys.add(bkey);
                    continue;
                }
                try{
                    Map<Integer,TMetaPo> platMap = new HashMap<>();
                    todoPos.forEach(d->{
                        platMap.put(d.plat,d);
                    });
                    List<Integer> keys = new ArrayList<>();
                    keys.add(XreaderConts.TMETA_PLAT_YNOTE);
                    keys.add(XreaderConts.TMETA_PLAT_GI);
                    keys.add(XreaderConts.TMETA_PLAT_CF);
                    Set<Integer> plats = platMap.keySet();
                    Set<Integer> extraPlats = plats.stream().filter(d->!keys.contains(d)).collect(Collectors.toSet());
                    keys.addAll(extraPlats);
                    for(Integer plat : keys){
                        TMetaPo platPo = platMap.get(plat);
                        if(platPo == null){
                            continue;
                        }
                        MetaTaskVo metaTaskVo = dealTMetaTaskBDoc(platPo);
                        TMetaPo downMetaPo = metaTaskVo.metaPo;
                        DLog.info("Middle>>>>>>>> bkey=",bkey,"dflag=",downMetaPo.dflag);
                        if(Objects.equals(downMetaPo.dflag,XreaderConts.TMETA_DLAG_OK)){
                            downOkBkeys.add(bkey);
                            break;
                        }
                        if(JkhlUtils.notBlank(metaTaskVo.msg) && metaTaskVo.msg.contains("No address associated with hostname")){
                            DLog.info("Down ErrMsg ===>",metaTaskVo.msg);
                            networkErr = true;
                        }

                    }
                }catch (Exception e){
                    DLog.error("bkey=",bkey,e.getMessage());
                    e.printStackTrace();
                }
                DLog.info("End Deal bkey=",bkey," 成功=",downOkBkeys.contains(bkey));
            }
            isOk = downOkBkeys.size() == bkeys.size();
        }catch (Exception e){
            e.printStackTrace();
            DLog.error("任务异常=",e.getMessage());
        }
        Long endTm = System.currentTimeMillis();
        DLog.info("btype最终计算结果：",btype,"Worker isOK=",isOk," 耗时=",(endTm-startTm)/1000," s");
        if(isOk){
            DDOC_TASKS.remove(btype);
        }
        //return isOk ? Result.success() : Result.failure();
        return isOk ? Result.success() : Result.retry();
    }


}
